package com.mynetwork.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;

import android.os.Environment;
import android.os.StatFs;
import android.text.TextUtils;
import android.util.Log;

public class FileUtils {
	private static final String TAG = "FileUtils";
	
	public static String PATH_SDCARD = Environment.getExternalStorageDirectory().getPath();

	//파일을 존재여부를 확인하는 메소드
	public static Boolean fileIsLive(String isLivefile) {
		File f1 = new File(isLivefile);
		
		if(f1.exists() && f1.isFile()) {
			return true;
		}else {
			return false;
		}
	}
	
	/**
	 * @brief 파일 이름 변경 
	 */
	public static boolean rename(String oldPath , String newPath){
		boolean result;
		File oldFile = new File(oldPath);
		File newFile = new File(newPath);
		if(oldFile!=null&&oldFile.exists()&&oldFile.renameTo(newFile)){
			result=true;
		}else{
			result=false;
		}
		return result;
	}
	
	/**
	 * @brief 파일을 생성하는 매소드 
	 */
	public static void fileMake(String makeFileName) {
		try {
			File f1 = new File(makeFileName);
			f1.createNewFile();
		} catch (Exception e) {
			Log.e("fileMake","" +  e);
		}
	}
	
	/**
	 * @brief 파일을 삭제하는 메소드
	 */
	public static void deleteFile(String deleteFileName) {
		if (deleteFileName != null) {
			File I = new File(deleteFileName);
			if (I.exists())
				I.delete();
		}
	}
	
	/**
	 * @brief 폴더 삭제
	 */
	public static void deleteFolder(String folder) {
        File file = new File(folder);
        if (!file.exists()) return;
        File[] childFileList = file.listFiles();
        if (childFileList == null)
        	return;
        for(File childFile : childFileList) {
            if(childFile.isDirectory()) {
            	deleteFolder(childFile.getAbsolutePath());
            } else {
                childFile.delete();
            }
        }
        
        file.delete();
    }
	
	/**
	 * @brief 파일을 복사하는 메소드
	 */
	public static boolean fileCopy(String oriPath, String targetPath) {
		if (oriPath == null || targetPath == null)
			return false;
		File oriFile = new File(oriPath);
	    File targetFile = new File(targetPath);
	    
	    
	    FileInputStream inputStream;
		try {
			inputStream = new FileInputStream(oriFile);
		    FileOutputStream outputStream = new FileOutputStream(targetFile);
	
		    FileChannel fcin =  inputStream.getChannel();
		    FileChannel fcout = outputStream.getChannel();
	
		    long size = fcin.size();
	
		    fcin.transferTo(0, size, fcout);
		    fcout.close();
		    fcin.close();
		    outputStream.close();
		    inputStream.close();
		} catch (Exception e) {
			Log.e("fileMake","" +  e);
			return false;
		}
	    return true;
	}
	
	/**
	 * @brief 폴더 복사
	 */
	public static void copyDirectory(String originalFolder, String newFolder){
		File sourceLocation = new File(originalFolder);
		File targetLocation = new File(newFolder);
		copyDirectory(sourceLocation, targetLocation);
	}
	
	/**
	 * @brief 폴더 복사
	 */
	public static void copyDirectory(File sourceLocation, File targetLocation) {		
	    if (sourceLocation.isDirectory()) {
	        if (!targetLocation.exists()) {
	            targetLocation.mkdir();
	        }

	        String[] children = sourceLocation.list();
	        for (int i=0; i<children.length; i++) {
	            copyDirectory(new File(sourceLocation, children[i]),
	                    new File(targetLocation, children[i]));
	        }
	    } else {
	        InputStream in;
			try {
				in = new FileInputStream(sourceLocation);
			
	        OutputStream out = new FileOutputStream(targetLocation);

	        // Copy the bits from instream to outstream
	        byte[] buf = new byte[1024];
	        int len;
	        
			while ((len = in.read(buf)) > 0) {
			    out.write(buf, 0, len);
			}

	        in.close();
	        out.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
	    }
	}
	
	/**
	 * @brief 파일을 이동하는 메소드
	 */
	public static void fileMove(String inFileName, String outFileName) {
		fileCopy(inFileName,outFileName);
		//복사한뒤 원본파일을 삭제함
		deleteFile(inFileName);

	}
	
	/**
	 * @brief 디렉토리의 파일 리스트를 읽는 메소드
	 */
	public static List<File> getDirFileList(String dirPath) {
		if (TextUtils.isEmpty(dirPath))
			return null;
		
		// 디렉토리 파일 리스트
		List<File> dirFileList = null;
		
		// 파일 목록을 요청한 디렉토리를 가지고 파일 객체를 생성함
		File dir = new File(dirPath);
		
		// 디렉토리가 존재한다면
		if (dir.exists()) {
			// 파일 목록을 구함
			File[] files = dir.listFiles();
			
			// 파일 배열을 파일 리스트로 변화함 
			if (files != null)
				dirFileList = Arrays.asList(files);
		}
		return dirFileList;
	}
	
	public static HashSet<String> getExternalMounts(){
    	final HashSet<String> out = new HashSet<String>();
        String reg = "(?i).*vold.*(vfat|ntfs|exfat|fat32|ext3|ext4).*rw.*";
        String s = "";
        try {
            final Process process = new ProcessBuilder().command("mount")
                    .redirectErrorStream(true).start();
            process.waitFor();
            final InputStream is = process.getInputStream();
            final byte[] buffer = new byte[1024];
            while (is.read(buffer) != -1) {
                s = s + new String(buffer);
            }
            is.close();
        } catch (final Exception e) {
            e.printStackTrace();
        }


        // parse output
        final String[] lines = s.split("\n");
        for (String line : lines) {
            if (!line.toLowerCase(Locale.US).contains("asec")) {
                if (line.matches(reg)) {
                    String[] parts = line.split(" ");
                    for (String part : parts) {
                        if (part.startsWith("/"))
                            if (!part.toLowerCase(Locale.US).contains("vold"))
                                out.add(part);
                    }
                }
            }
        }
        return out;
    }
	
	//확장자 얻기
	public static String getExtension(String fileStr) {
		if (fileStr == null || fileStr.lastIndexOf(".") < 0) {
			return "";
		}
		return fileStr.substring(fileStr.lastIndexOf(".")+1,fileStr.length());
	}
	
	public static String getFileName(String fileStr) {
		String fileName = fileStr.substring(fileStr.lastIndexOf("/")+1,fileStr.length());
		if (fileName.lastIndexOf(".") > 0)
			return fileName.substring(0,fileName.lastIndexOf("."));
		else
			return fileName;
	}
	
	public static String getName(String fileStr) {
		return fileStr.substring(fileStr.lastIndexOf("/")+1,fileStr.length());
	}
	
	public static long getSDCardStorageByte(String path) {
		 StatFs stat = new StatFs(path);
       return (long) stat.getFreeBlocks()* (long)stat.getBlockSize();
	}
	
	public static long getSDCardStorageMB(String path) {
      return getSDCardStorageByte(path) / 1024 / 1024; 
	}
}
